package com.qianfeng.smartdevices.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qianfeng.smartdevices.cache.LogDataCache;
import com.qianfeng.smartdevices.event.LogDataChangeEvent;
import com.qianfeng.smartdevices.mapper.LogMapper;
import com.qianfeng.smartdevices.pojo.LogData;
import com.qianfeng.smartdevices.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class LogServiceImpl implements LogService {

    private LogMapper logMapper;
    private LogDataCache logDataCache;
    private ApplicationContext context;
    @Autowired
    public void setLogDataCache(LogDataCache logDataCache) {
        this.logDataCache = logDataCache;
    }
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setLogMapper(LogMapper logMapper) {
        this.logMapper = logMapper;
    }

//    @Override
//    public List<LogData> findAll() {
//        List<LogData> allLogs = logMapper.findAllLogs();
//        return allLogs;
//    }

    @Override
    public void addLogData(LogData logData) {
        logMapper.addLogData(logData);
        context.publishEvent(new LogDataChangeEvent());
    }

    @Override
    public void updateLogData(LogData logData) {
        logMapper.updateLogData(logData);
        context.publishEvent(new LogDataChangeEvent());
    }

    @Override
    public void deleteLogData(Long[] ids) {
        logMapper.deleteLogData(Arrays.asList(ids));
        context.publishEvent(new LogDataChangeEvent());
    }

    @Override
    public PageInfo<LogData> findLogDataByPage(int page, int limit,String user,String msg) {
        PageHelper.startPage(page, limit);
        List<LogData> logDataList = logMapper.findAllLogs(user,msg);
        return new PageInfo<>(logDataList);
//        List<LogData> allData = logDataCache.getAllData();
//        List<LogData> subList = allData.stream().filter(logData -> {
//            boolean b1 = ObjectUtils.isEmpty(user) ? true : logData.getUser().contains(user);
//            boolean b2 = (ObjectUtils.isEmpty(msg) || msg.equals("-100")) ? true : logData.getMsg().contains(msg);
//
//            return b1 && b2;
//        }).collect(Collectors.toList());
//        List<LogData> list = subList.stream().skip((page - 1) * limit).limit(limit).collect(Collectors.toList());
//        PageInfo<LogData> pageInfo = new PageInfo<>(list);
//        pageInfo.setTotal(subList.size());
//        return pageInfo;

    }
}
